package com.codegravity.mobile.expensms;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SMSExpenseTrackingActivity extends Activity {
	final static String smsInbox = "content://sms/inbox";
	Button btn_filter, btn_expense, btn_import, btn_help;
	String testRes = "";
	String s_number, s_debstr, s_decimal;
	SharedPreferences myPrefs;
	ArrayList<Long> db_dates;
	ArrayList<String> db_amnt;
	String dbColumns[] = { "_id", "thread_id", "address", "person", "date",
			"body" };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myPrefs = getSharedPreferences("SMSExpense", MODE_WORLD_READABLE);

		if (myPrefs.getBoolean("disagree", true))
			showDialog(0);
		setContentView(R.layout.main);
		btn_expense = (Button) findViewById(R.id.btn_view_expense);
		btn_expense.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SMSExpenseTrackingActivity.this,
						ChartsGallery.class);
				startActivity(intent);

			}
		});
		btn_filter = (Button) findViewById(R.id.btn_filter);
		btn_filter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SMSExpenseTrackingActivity.this,
						Filter.class);
				startActivity(intent);
			}
		});
		btn_import = (Button) findViewById(R.id.btn_import);
		btn_import.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				handleImport();
			}
		});
		btn_help = (Button) findViewById(R.id.btn_show_help);
		btn_help.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(1);
			}
		});
	}

	private void handleImport() {
		Toast.makeText(getApplicationContext(), "Please Wait....",
				Toast.LENGTH_SHORT).show();
		s_number = myPrefs.getString("keynum", "");
		s_debstr = myPrefs.getString("keystr", "");
		s_decimal = myPrefs.getString("keydec", ".");

		String SORT_ORDER = "date DESC";
		String whereClause = "address like '" + s_number + "'";

		loadExpenses();

		Cursor cursor = getApplicationContext().getContentResolver().query(
				Uri.parse(smsInbox), dbColumns, whereClause, null, SORT_ORDER);
		int importCnt = extractRecords(cursor);
		cursor.close();
		String MSG = "Total Messages imported " + importCnt;
		Toast.makeText(getApplicationContext(), MSG, Toast.LENGTH_SHORT).show();
	}

	private Exception dbError = new Exception("DB ACESS ERROR");

	private int extractRecords(Cursor cursor) {
		int importCnt = 0;
		try {
			checkCur(cursor);
			cursor.moveToFirst();
			s_debstr = myPrefs.getString("keystr", "");
			do {
				if (!s_number.equals(cursor.getString(2)))
					continue;
				int idx1 = cursor.getString(5).indexOf(s_debstr);
				if (idx1 == -1)
					continue;
				int idx2 = cursor.getString(5).indexOf("\n", idx1);
				if (idx2 == -1)
					idx2 = cursor.getString(5).length();
				Pattern MY_PATTERN = Pattern
						.compile("[0-9|" + s_decimal + "]+");
				Matcher m = MY_PATTERN.matcher(cursor.getString(5).substring(
						idx1, idx2));
				long date = 0;
				float amount = 0;
				while (m.find()) {
					amount = Float.parseFloat(m.group().replaceAll(",", "."));
					date = cursor.getLong(4);
					if (checkMatch(amount, date))
						break;
					createRecord(date, amount);
					importCnt++;
					break;
				}
			} while (cursor.moveToNext());
		} catch (Exception e) {
			return -1;
		}
		return importCnt;
	}

	private void checkCur(Cursor cursor) throws Exception {
		if (cursor == null)
			throw dbError;
		int count = cursor.getCount();
		if (count <= 0)
			throw dbError;
	}

	private void createRecord(long date, float amount) {
		ExpenseDataBase db = new ExpenseDataBase(getApplicationContext());
		db.open();
		db.createAlert(ExpenseDataBase.EXPENSE_TABLE,
				ExpenseDataBase.EXPENSE_INT, new String[] { "" + amount,
						"" + date });
		db.close();
	}

	private boolean checkMatch(float amount, long date) {
		if (db_dates.contains(date)) {
			db_amnt.get(db_dates.indexOf(date)).equals(amount);
			return true;
		}
		return false;
	}

	private void loadExpenses() {
		db_dates = new ArrayList<Long>();
		db_amnt = new ArrayList<String>();

		ExpenseDataBase dbase = new ExpenseDataBase(getApplicationContext());
		dbase.open();
		Cursor db_cur = dbase.fetchAllAlerts(ExpenseDataBase.EXPENSE_TABLE,
				ExpenseDataBase.EXPENSE_INT);
		if (db_cur != null && db_cur.getCount() > 0) {
			db_cur.moveToFirst();
			do {
				db_dates.add(db_cur.getLong(2));
				db_amnt.add(db_cur.getString(1));
			} while (db_cur.moveToNext());
		}
		dbase.close();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog dialog = null;
		AlertDialog.Builder alertBuilder;
		switch (id) {
		case 0:
			alertBuilder = new AlertDialog.Builder(this);

			alertBuilder.setTitle("License Agreement");
			alertBuilder.setMessage(getResources()
					.getString(R.string.txt_license).replaceAll("~lt~", "<")
					.replaceAll("~gt~", ">"));
			alertBuilder.setPositiveButton("I Agree",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							dialog.dismiss();
							SharedPreferences.Editor prefsEditor = myPrefs
									.edit();
							prefsEditor.putBoolean("disagree", false);
							prefsEditor.commit();
						}
					});

			alertBuilder.setNegativeButton("Disagree",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							dialog.dismiss();
							System.exit(0);
						}
					});
			alertBuilder.setIcon(R.drawable.icon);
			dialog = alertBuilder.create();
			dialog.setCancelable(false);
			dialog.show();
			return dialog;

		case 1:
			dialog = null;
			alertBuilder = new AlertDialog.Builder(this);

			alertBuilder.setTitle("Help");
			alertBuilder
					.setMessage(Html.fromHtml(getResources().getString(R.string.txt_help)));
			alertBuilder.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							dialog.dismiss();
						}
					});
			alertBuilder.setIcon(R.drawable.icon);
			dialog = alertBuilder.create();
			
			dialog.setCancelable(false);
			dialog.show();
			return dialog;
		default:
			break;
		}
		return null;
	}
}